Ext.namespace("TR.admin.security");

TR.admin.security.role = function(panelId, title, iconClz){
	var allModule = [];
	var clientControlTreeable = true;
	ajaxRequest({
		url : "admin/module/allModuleAndCommand",
		callback : function(json){
			allModule = $.makeArray(json.data.allModule);
			allCommand = $.makeArray(json.data.allCommand);
			initModuleTree();
		}
	});

	var optBar = [{
		text : "创建",
		iconCls: "create",
		handler : function(){
			addRole("admin/role/add");
		}
	}, "-", {
		text : "删除",
		iconCls : "delete",
		handler : function(){
			if(sm.getSelected()==undefined || sm.getSelected()==null){
				showFailMsg("请选择角色");
				return;
			}
			confirmDelete(delRole);
			function delRole(){
				var selectedRoleId = sm.getSelected().get("id");
				ajaxRequest({
					url : "admin/role/delete/" + selectedRoleId,
					callback : function(){
						roleStore.reload();
						troot.cascade(function(r){
							if(!r.hasChildNodes()){
								var cId = r.attributes.cId;
								if(cId!=undefined){
									var checkUI = r.getUI();
									if(checkUI.isChecked()){
										checkUI.toggleCheck(false);
									}
								}
							}
						});
					}
				});
			}
		}
	}, "-",{
		text : "更新",
		iconCls : "update",
		handler : function(){
			updateRole("admin/role/update");
		}
	}, "-", {
		text : "切换状态",
		iconCls : "toggleStatus",
		handler : function(){
			var rec = sm.getSelected();
			if(rec===undefined){
				showFailMsg("请选择角色.");
				return;
			}
			ajaxRequest({
				url : "admin/role/toggleStatus/" + rec.get("id"),
				showMsg : "切换状态成功.",
				callback : function(){
					roleStore.reload();
				}
			});
		}
	}];
	var queryField = genQueryField();
	var queryBar = [queryField, {
		text : "查询",
		iconCls : "query",
		handler : function(){
			roleStore.load();
		}
	}];
	var roleStore = new Ext.data.JsonStore({
		url : "admin/role/findRoleByCon",
		totalProperty : "total",
		root : "rows",
		autoLoad : true,
		fields : ["id", "createTime", "updateTime", "des", "roleName", "isRoot", "status"],
		listeners : {
			"beforeload" : function(s){
				s.removeAll();
				Ext.apply(s.baseParams, {
					con : queryField.getValue()
				});
			}
		}
	});
	var roleCm = new Ext.grid.ColumnModel([{
		header : "名称",
		dataIndex : "roleName"
	}, {
		header : "状态",
		dataIndex : "status"
	}, {
		header : "描述",
		dataIndex : "des"
	}]);
	var troot = new Ext.tree.TreeNode({
		text : "root"
	});

	var sm = new Ext.grid.RowSelectionModel({
		singleSelect : true,
		listeners : {
			"rowselect" : function(_sm){
				var rId = _sm.getSelected().get("id");
				ajaxRequest({
					url: "admin/command/listCommandByRole/" + rId,
					callback : refreshTree
				});
				function refreshTree(json){
					var roleCommand = $.makeArray(json.data);
					troot.cascade(function(r){
						clientControlTreeable = false;
						if(!r.hasChildNodes()){
							var cId = r.attributes.cId;
							if(cId!=undefined){
								var checkUI = r.getUI();
								if(checkUI.isChecked()){
									checkUI.toggleCheck(false);
								}
								$.each(roleCommand, function(n, v){
									var commandId = v.id;
									if(commandId!=undefined && cId==commandId){
										checkUI.toggleCheck(true);
									}
								});
							}
						}
						clientControlTreeable = true;
					});
				}
			}
		}
	});
	var roleGrid = new Ext.grid.GridPanel({
		title : "系统全部角色",
		flex : 1,
		store : roleStore,
		cm : roleCm,
		sm : sm,
		frame : true,
		autoScroll : true,
		tbar : genToolBar(optBar, queryBar, panelId),
		bbar : genPageBar(roleStore)
	});

	var commandTreePanel = new Ext.tree.TreePanel({
		title : "角色的操作权限",
		flex : 1,
		frame : true,
		root : troot,
		autoScroll : true,
		rootVisible : false,
		listeners : {
			"checkchange" : function(node, checked){
				var rec = sm.getSelected();
				if(rec==undefined){
					return;
				}
				if(clientControlTreeable){
					ajaxRequest({
						url : "admin/role/toggleRoleCommand",
						params : {
							roleId : rec.get("id"),
							commandId : node.attributes.cId,
							checked : checked
						}
					});
				}
			}
		}
	});
	return new Ext.Panel({
		id : panelId,
		title : title,
		iconCls : iconClz,
		closable : true,
		layout : "hbox",
		layoutConfig : {
			align : "stretch"
		},
		items : [roleGrid, commandTreePanel]
	});

	//根据全部module生成完整的module tree
	function initModuleTree(){
		var levelOne = $.grep(allModule, function(o){
			return o.parent==null
		});
		//1.生成module tree
		$.each(levelOne, function(n, v){
			var mNode = new Ext.tree.TreeNode({
				mId : v.id,
				text : v.chinese,
				iconCls : v.iconClz,
				expanded : true
			});
			troot.appendChild(mNode);
			addChildren(v, mNode);

			function addChildren(p, root){
				$.each(allModule, function(n, m){
					if(m.parent!=null && m.parent.id== p.id){
						var child = new Ext.tree.TreeNode({
							mId : m.id,
							text : m.chinese,
							iconCls : m.iconClz,
							expanded : true
						});
						root.appendChild(child);
						addChildren(m, child);
					}
				});
			}
		});
		//2.添加command
		troot.cascade(function(r){
			if(!r.hasChildNodes()){
				//后面动态添加troot里的节点也会被cascade
				var mId = r.attributes.mId;
				if(mId!=undefined){
					$.each(allCommand, function(n, v){
						var moduleId = v.module.id;
						if(moduleId!=undefined && mId==moduleId){
							var _n = new Ext.tree.TreeNode({
								cId : v.id,
								text : v.chinese,
								iconCls : v.iconClz,
								expanded : true,
								checked : false
							});
							r.appendChild(_n);
						}
					});
				}
			}
		});
		commandTreePanel.expandAll();
	}

	function genAddOrUpdateWindow(url){
		return new Ext.Window({
			title : "新增或修改角色",
			layout : "fit",
			modal : true,
			iconCls : "save",
			width : 300,
			height : 160,
			plain : true,
			bodyStyle : 'padding:5px;',
			items : genForm(url)
		});
	}

	function genForm(url){
		return new Ext.form.FormPanel({
			url : url,
			labelWidth : 60,
			labelAlign : "right",
			baseCls: 'x-plain',
			defaults : {
				xtype : "textfield",
				anchor : "95%"
			},
			items : [{
				xtype : "hidden",
				name : "id",
				//value设置-1，为空则controller检验失败
				value : "-1"
			}, {
				fieldLabel : "角色名称",
				allowBlank : false,
				name : "roleName"
			}, genStatusCombo(), {
				fieldLabel : "描述",
				name : "des"
			}],
			buttonAlign : "center",
			buttons : [{
				text : "保存",
				iconCls : "save",
				handler : function(b){
					submitForm(b.findParentByType("form"), refreshGrid);
					function refreshGrid(){
						roleStore.reload();
					}
				}
			}, {
				text : "重置",
				iconCls : "reset",
				type : "reset",
				handler : function(b){
					b.findParentByType("form").getForm().reset();
				}
			}]
		});
	}

	function addRole(url){
		var win = genAddOrUpdateWindow(url);
		win.show();
	}
	function updateRole(url){
		var rec = sm.getSelected();
		if(rec==undefined){
			showFailMsg("请选择角色");
			return;
		}
		var win = genAddOrUpdateWindow(url);
		win.findByType("form")[0].getForm().loadRecord(rec);
		win.show();
	}
}

registerModule("TR.admin.security.role", TR.admin.security.role);